template
<template>
  <div class="clearfix">
    <a-upload
      :action="uploadImgUrl"
      :list-type="listType"
      :show-upload-list="true"
      :headers="headers"
      :multiple="multiple"
      :before-upload="beforeUpload"
      :file-list="fileList"
      @change="handleChange"
    >
      <div v-if="fileList.length < count">
        <span v-if="type === 'image'">
          <a-icon :type="loading ? 'loading' : 'plus'" />
          <div class="ant-upload-text">上传</div>
        </span>
      </div>
      <div v-if="type === 'file'">
        <a-button :disabled="fileList.length >= count">
          <a-icon type="upload" /> 上传
        </a-button>
      </div>
    </a-upload>
  </div>
</template>

<script>
import storage from 'store';
import { ACCESS_TOKEN } from '@/store/mutation-types';

export default {
  name: 'ImageUpload',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'image'
    },
    count: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      loading: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      fileList: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (typeof newVal === 'string') newVal = newVal.split(',')
        this.fileList = newVal.map(url => ({
          uid: url,
          response: {
            fileName: url
          },
          name: url.split(',').pop(),
          status: 'done',
          url: url
        }))
      }
    }
  },
  computed: {
    listType() {
      return this.type === 'image' ? 'picture-card' : 'text'
    },
    multiple() {
      return this.count > 1
    }
  },
  methods: {
    handleChange({ file, fileList }) {
      this.fileList = JSON.parse(JSON.stringify(fileList))
      if (file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (file.status === 'done') {
        if (file.response.code !== 200) {
          this.$message.error('上传失败: ' + file.response.msg)
          this.loading = false
          return;
        }
        this.loading = false
        this.$emit('input', fileList.map(fil => fil.response.fileName).join(','));
      } else if (file.status === 'removed') {
        this.$emit('input', fileList.map(fil => fil.response.fileName).join(','));
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('文件大小限制为 2MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
img {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
